var app = getApp();
var WxParse = require("../../lib/wxParse/wxParse.js");
var util = require("../../utils/util.js");
var api = require("../../config/api.js");
const user = require("../../services/user.js");
const ctx = wx.createCanvasContext("shareCanvas");
let setTimerId = null;

Page({
    data: {
        parentOrderId:null,
        isGroupBuying: false,
        backTop: 30,
        latitude: "",
        longitude: "",
        addressInfo: null,
        timer: null,
        orderGoods: [],
        Height: 0,
        timeLeft: 0,
        scale: 17,
        priceLeft: "0",
        priceRight: "00",
        latitude: "",
        longitude: "",
        markers: [],
        circles: [],
        timeTo: 0,
        id: 0,
        goods: {},
        retailPrice: "",
        gallery: [],
        attribute: [],
        showCanvas: false,
        issueList: [],
        comment: [],
        wxaCodeImg: null,
        brand: {},
        specificationList: [],
        productList: [],
        relatedGoods: [],
        cartGoodsCount: 1,
        userHasCollect: 0,
        btnAddSlide: false,
        number: 1,
        checkedSpecText: "请选择规格",
        openAttr: false,
        indexImg:
            "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/icon_home.png",
        picUrl: null,
        isFinished: false,
        remainingSecondsArr: [], //有活动的剩余时间
        activityNum: 0, // 有活动的商品数量
    },
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh();
    },
    onShareAppMessage: function () {
        return {
            title: '这个商品真的太划算了，我已经下单了！',
            imageUrl:this.data.goods.sharePoster,
            path:
                "/pages/goods/goods?id=" +
                this.data.id +
                "&recommend_id=" +
                wx.getStorageSync("userInfo").id,
        };
    },
    goback() {
        wx.navigateBack();
    },
    changeAddSlide: function () {
        if (this.data.btnAddSlide) {
            this.setData({
                btnAddSlide: false,
            });
        } else {
            this.setData({
                btnAddSlide: true,
            });
        }
    },
    getGoodsInfo: function () {
        wx.showLoading({
            title: "正在加载",
        });
        let that = this;
        util.request(
            api.commodityDetail,
            { commodityId: that.data.id },
            "GET"
        ).then(function (res) {
            if (res.code == 200) {
                const remainingSecondsArr = [],
                    result = res.result;
                let activityNum = 0;
                wx.hideLoading();
                that.setData({
                    goods: result,
                    picUrl: result.poster,
                    gallery: result.commodityAlbumList,
                });
                if (result.remainingSeconds > 0) {
                    activityNum++;
                }
                remainingSecondsArr.push(result.remainingSeconds);
                let sellingPrice = result.sellingPrice.toString();
                // if (result.endTime) {
                //     that.setData({
                //         timeTo: result.endTime,
                //     });
                // }
                let priceLeft = sellingPrice.split(".")[0];

                let priceRight = "00";
                if (sellingPrice.split(".")[1]) {
                    priceRight = sellingPrice.split(".")[1];
                }

                that.setData({
                    priceLeft: priceLeft,
                    priceRight: priceRight,
                    isFinished: true,
                    remainingSecondsArr,
                    activityNum,
                });
                // 有活动商品且时间差不为0
                if (activityNum > 0) {
                    that.minusRemainingSeconeds();
                }
                if (result.detail) {
                    WxParse.wxParse("goodsDetail", "html", result.detail, that);
                }
            }
        });
    },

    getAddressInfoList: function () {
        let _this = this;

        wx.getLocation({
            type: "wgs84",
            success: function (res) {
                util.request(
                    api.findAddressInfoList +
                        "?lat=" +
                        res.latitude +
                        "&lon=" +
                        res.longitude
                )
                    .then((result) => {
                        const chooseItem = result.result.find(item => item.isChoose) || result.result[0];
                        _this.setData({
                            addressInfo: chooseItem,

                            markers: [
                                {
                                    id: "1",
                                    latitude: chooseItem.lat,
                                    longitude: chooseItem.lon,
                                    width: 30,
                                    height: 30,
                                    iconPath:
                                        "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/icon_position.png",
                                    title:
                                        chooseItem.storeName +
                                        "|" +
                                        chooseItem.storeAddress,
                                },
                            ],
                            circles: [
                                {
                                    latitude: chooseItem.lat,
                                    longitude: chooseItem.lon,
                                    color: "#FF0000DD",
                                    fillColor: "#7cb5ec88",
                                    radius: 100,
                                    strokeWidth: 1,
                                },
                            ],
                        });
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
            fail: function (err) {
                console.log(333, err);
            },
        });
    },
    saveShareImg: function () {
        const wxCanvasToTempFilePath = util.wxPromisify(
            wx.canvasToTempFilePath
        );
        const wxSaveImageToPhotosAlbum = util.wxPromisify(
            wx.saveImageToPhotosAlbum
        );
        wxCanvasToTempFilePath(
            {
                canvasId: "shareCanvas",
            },
            this
        )
            .then((res) => {
                return wxSaveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                });
            })
            .then((res) => {
                wx.showToast({
                    title: "已保存到相册",
                });
                _this.setData({
                    showCanvas: false,
                });
            });
    },
    goAddress() {
        if (app.globalData.userInfo && app.globalData.userInfo.phone) {
            wx.navigateTo({
                url: "/pages/addressList/addressList",
            });
            return;
        }
        this.goLogin();
    },
    getWxaCodeUnlimit: function () {
        let _this = this;
        let recommend_id = wx.getStorageSync("userInfo").id || 15;
        util.request(
            api.GetWxaCodeUnlimit,
            {
                page:
                    "pages/goods/goods?id=" +
                    _this.data.id +
                    "&recommend_id=" +
                    recommend_id,
            },
            "POST"
        ).then(function (res) {
            if (res.errno === 0) {
                _this.setData({
                    wxaCodeImg: res.data.filename,
                });
            }
        });
    },
    drawImageWxCode: function () {
        wx.showLoading({
            title: "生成图片...",
        });
        let _this = this;
        const wxGetImageInfo = util.wxPromisify(wx.getImageInfo);
        let recommend_id = wx.getStorageSync("userInfo").id || 15;

        Promise.all([
            wxGetImageInfo({
                src: _this.data.gallery[0].img_url,
            }),
            wxGetImageInfo({
                src: _this.data.wxaCodeImg,
            }),
        ]).then((res) => {
            // 底图
            ctx.setFillStyle("#ffffff");
            ctx.fillRect(0, 0, 1000, 1000);
            ctx.drawImage(res[0].path, 60, 70, 180, 180);
            // 作者名称
            ctx.setTextAlign("center"); // 文字居中
            ctx.setFillStyle("#000000"); // 文字颜色：黑色
            ctx.setFontSize(12); // 文字字号：22px
            ctx.fillText(_this.data.goods.name, 130, 40);
            ctx.setTextAlign("center"); // 文字居中
            ctx.setFillStyle("#ff3300"); // 文字颜色：红色
            ctx.setFontSize(22);
            ctx.fillText("价格：¥" + _this.data.goods.retail_price, 80, 350);
            ctx.drawImage(res[1].path, 190, 290, 100, 100);
            // 小程序码
            ctx.stroke();
            ctx.draw();
            _this.setData({
                showCanvas: true,
            });
            wx.hideLoading();
        });
    },
    clickSkuValue: function (event) {
        let that = this;
        let specNameId = event.currentTarget.dataset.nameId;
        let specValueId = event.currentTarget.dataset.valueId;
        //判断是否可以点击

        //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
        let _specificationList = this.data.specificationList;
        for (let i = 0; i < _specificationList.length; i++) {
            if (_specificationList[i].specification_id == specNameId) {
                for (
                    let j = 0;
                    j < _specificationList[i].valueList.length;
                    j++
                ) {
                    if (_specificationList[i].valueList[j].id == specValueId) {
                        //如果已经选中，则反选
                        if (_specificationList[i].valueList[j].checked) {
                            _specificationList[i].valueList[j].checked = false;
                        } else {
                            _specificationList[i].valueList[j].checked = true;
                        }
                    } else {
                        _specificationList[i].valueList[j].checked = false;
                    }
                }
            }
        }
        this.setData({
            specificationList: _specificationList,
        });
        //重新计算spec改变后的信息
        this.changeSpecInfo();
        //重新计算哪些值不可以点击
    },
    gotoIndex: function () {
        wx.switchTab({
            url: "/pages/index/index",
        });
    },
    //获取选中的规格信息
    getCheckedSpecValue: function () {
        let checkedValues = [];
        let _specificationList = this.data.specificationList;
        for (let i = 0; i < _specificationList.length; i++) {
            let _checkedObj = {
                nameId: _specificationList[i].specification_id,
                valueId: 0,
                valueText: "",
                picUrl: "",
                retailPrice: "",
            };
            for (let j = 0; j < _specificationList[i].valueList.length; j++) {
                if (_specificationList[i].valueList[j].checked) {
                    _checkedObj.valueId = _specificationList[i].valueList[j].id;
                    _checkedObj.valueText =
                        _specificationList[i].valueList[j].value;
                    _checkedObj.picUrl =
                        _specificationList[i].valueList[j].pic_url;
                    _checkedObj.retailPrice =
                        this.data.productList[j].retail_price;
                }
            }

            checkedValues.push(_checkedObj);
        }

        return checkedValues;
    },
    //根据已选的值，计算其它值的状态
    setSpecValueStatus: function () {},
    //判断规格是否选择完整
    isCheckedAllSpec: function () {
        return !this.getCheckedSpecValue().some(function (v) {
            if (v.valueId == 0) {
                return true;
            }
        });
    },
    getCheckedSpecKey: function () {
        let checkedValue = this.getCheckedSpecValue().map(function (v) {
            return v.valueId;
        });
        return checkedValue.join("_");
    },
    changeSpecInfo: function () {
        let checkedNameValue = this.getCheckedSpecValue();
        //设置选择的信息
        let checkedValue = checkedNameValue
            .filter(function (v) {
                if (v.valueId != 0) {
                    return true;
                } else {
                    return false;
                }
            })
            .map(function (v) {
                return v.valueText;
            });
        let picUrl = checkedNameValue
            .filter(function (v) {
                if (v.valueId != 0) {
                    return true;
                } else {
                    return false;
                }
            })
            .map(function (v) {
                return v.picUrl;
            });
        let specification_ids = checkedNameValue
            .filter(function (v) {
                if (v.valueId != 0) {
                    return true;
                } else {
                    return false;
                }
            })
            .map(function (v) {
                return v.valueId;
            });

        let goods_ids = specification_ids.join("_");
        let productObj = this.data.productList.find((v) => {
            return v.goods_specification_ids == goods_ids;
        });
        let retailPrice = this.data.productList[0].retail_price;
        if (productObj) {
            retailPrice = productObj.retail_price;
        }

        if (checkedValue.length > 0) {
            this.setData({
                checkedSpecText: checkedValue.join("　"),
            });
            if (picUrl != "") {
                this.setData({
                    picUrl: picUrl[0],
                });
            }
            this.setData({
                retailPrice: retailPrice,
            });
        } else {
            this.setData({
                checkedSpecText: "请选择规格",
            });
        }
    },
    //显示对话框
    showModal: function () {
        // 显示遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0,
        });
        this.animation = animation;
        animation.translateY(300).step();
        this.setData({
            animationData: animation.export(),
            openAttr: true,
        });
        setTimeout(
            function () {
                animation.translateY(0).step();
                this.setData({
                    animationData: animation.export(),
                });
            }.bind(this),
            200
        );
    },

    //隐藏对话框
    hideModal: function () {
        // 隐藏遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0,
        });
        this.animation = animation;
        animation.translateY(300).step();
        this.setData({
            animationData: animation.export(),
        });
        setTimeout(
            function () {
                animation.translateY(0).step();
                this.setData({
                    animationData: animation.export(),
                    openAttr: false,
                    showCanvas: false,
                });
            }.bind(this),
            200
        );
    },
    getCheckedProductItem: function (key) {
        return this.data.productList.filter(function (v) {
            if (v.goods_specification_ids == key) {
                return true;
            } else {
                return false;
            }
        });
    },
    onLoad: function (options) {
        let orderId = options.orderId;
        if(orderId){
            this.setData({
                parentOrderId:orderId
            })
        }
        // 页面初始化 options为页面跳转所带来的参数
        try {
            wx.removeStorageSync("couponId");
            let couponId = wx.getStorageSync("couponId");
        } catch (e) {
            // Do something when catch error
        }
        let link = decodeURIComponent(options.q);

        if (!!options.id) {
            this.setData({
                id: parseInt(options.id),
                // id: 1181000
            });
        } else if (link) {
            let paramArr = link.split("=");
            this.setData({
                id: parseInt(paramArr[1]),
                // id: 1181000
            });
        }

        if (!!options.recommend_id) {
            wx.setStorageSync("recommendId", options.recommend_id);
        }
        var that = this;
        this.getGoodsInfo();
        this.getCartNum();
        // this.getWxaCodeUnlimit();
    },
    onReady: function () {
        // 页面渲染完成
    },
    getCartNum() {
        let _this = this;
        util.request(api.cartUrl.cartList).then(function (res) {
            if (res.code == 200) {
                _this.setData({
                    cartGoodsCount: (res.result && res.result.count) || 0,
                });
            }
        });
    },
    onShow: function () {
        this.setData({
            backTop: app.globalData.navHeight - 38,
        });
        let userInfo = wx.getStorageSync("userInfo");
        let token = wx.getStorageSync("token");
        if (userInfo && token) {
            app.globalData.userInfo = userInfo;
            app.globalData.token = token;
        }
        // 页面显示
        this.data.timer = setInterval(() => {
            //注意箭头函数！！
            this.setData({
                timeLeft: util.getTimeLeft(this.data.timeTo), //使用了util.getTimeLeft
            });
            if (this.data.timeLeft == 0) {
                clearInterval(this.data.timer);
            }
        }, 1000);

        this.getAddressInfoList();
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
        clearTimeout(setTimerId)
    },
    switchAttrPop: function () {
        if (this.data.openAttr == false) {
            this.setData({
                openAttr: !this.data.openAttr,
            });
        }
    },
    closeAttrOrCollect: function () {
        let that = this;
        if (this.data.openAttr) {
            this.setData({
                openAttr: false,
            });
            if (that.data.userHasCollect == 1) {
                that.setData({
                    collectClass: "collectIcon",
                });
            } else {
                that.setData({
                    collectClass: "noCollectIcon",
                });
            }
        } else {
            //添加或是取消收藏
            util.request(
                api.CollectAddOrDelete,
                { typeId: 0, valueId: this.data.id },
                "POST"
            ).then(function (res) {
                let _res = res;
                if (_res.errno == 0) {
                    if (_res.data.type == "add") {
                        that.setData({
                            collectClass: "collectIcon",
                        });
                    } else {
                        that.setData({
                            collectClass: "noCollectIcon",
                        });
                    }
                } else {
                    wx.showToast({
                        image: "/static/images/icon_error.png",
                        title: _res.errmsg,
                        mask: true,
                    });
                }
            });
        }
    },
    openCartPage: function () {
        wx.switchTab({
            url: "/pages/cart/cart",
        });
    },
    nowBuy: function () {
        this.addToCart(1);
    },
    checkoutOrder: function (isGroup = true) {
        let that = this;
        if (!app.globalData.userInfo || !app.globalData.userInfo.phone) {
            this.goLogin();
            return;
        }
        console.log(111, that.data.goods)
        let orderGoodsList = [
            {

                isMail: that.data.goods.isMail,
                activity: true,
                commodityId: that.data.goods.commodityId,
                markingPrice: that.data.goods.markingPrice,
                name: that.data.goods.name,
                poster: that.data.goods.poster,
                quantity: that.data.number,
                savingPrice:
                    that.data.goods.markingPrice - that.data.goods.sellingPrice,
                sellingPrice: that.data.goods.sellingPrice,
            },
        ];
        if(this.data.parentOrderId){
            orderGoodsList[0].parentOrderId = this.data.parentOrderId;
        }
        wx.setStorageSync("orderGoodsList", orderGoodsList);
        let url = "/pages/orderPay/orderPay?activityType=" + that.data.goods.activityType.value;
        if(!isGroup){
            url += "&isGroup=true"
            //订阅消息
            let templIds = ['yfiLzXA9_Ve5222lIifRHDQu5ub3v3mQNeYGjmrGO_w']
            wx.requestSubscribeMessage({
                tmplIds: templIds,
                success (res) {
                    console.log(res)
                    wx.navigateTo({
                        url: url,
                    });
                },
                fail (err) {
                    console.log(err)
                    wx.navigateTo({
                        url: url,
                    });
                }
            })
        } else {
            wx.navigateTo({
                url: url,
            });
        }

    },
    goLogin() {
        wx.navigateTo({
            url: "/pages/authorized/index",
        });
    },
    addToCart: function (nowBuy) {
        var that = this;
        if (this.data.openAttr == false) {
            //打开规格选择窗口
            this.showModal();
        } else {
            var cartAddPram = {
                commodityId: this.data.goods.commodityId,
                quantity: this.data.number,
            };
            if (nowBuy == 1) {
                if (
                    !app.globalData.userInfo ||
                    !app.globalData.userInfo.phone
                ) {
                    this.goLogin();
                }
                let orderGoodsList = [
                    {
                        activity: true,
                        commodityId: that.data.goods.commodityId,
                        markingPrice: that.data.goods.markingPrice,
                        name: that.data.goods.name,
                        poster: that.data.goods.poster,
                        quantity: that.data.number,
                        savingPrice:
                            that.data.goods.markingPrice -
                            that.data.goods.sellingPrice,
                        sellingPrice: that.data.goods.sellingPrice,
                    },
                ];
                wx.setStorageSync("orderGoodsList", orderGoodsList);
                wx.navigateTo({
                    url: "/pages/orderPay/orderPay",
                });
            } else {
                //添加到购物车
                util.request(api.cartUrl.cartUpdate, cartAddPram, "POST").then(
                    function (res) {
                        let _res = res;
                        if (_res.code == 200) {
                            wx.showToast({
                                title: "添加成功",
                            });
                            app.globalData.cartNum = res.result;
                        } else {
                            wx.showToast({
                                image: "/static/images/icon_error.png",
                                title: _res.errmsg,
                                mask: true,
                            });
                            that.getCartNum();
                        }
                    }
                );
            }
        }
    },
    cutNumber: function () {
        this.setData({
            number: this.data.number - 1 > 1 ? this.data.number - 1 : 1,
        });
    },
    addNumber: function () {
        this.setData({
            number: this.data.number + 1,
        });
    },
    groupBuy() {
        // wx.navigateTo({
            // url: "/pages/groupBuyingShare/groupBuyingShare",
        // });
        this.checkoutOrder(false);
    },
    aloneBuy() {
        wx.navigateTo({
            url: "/pages/groupBuyingShareGood/groupBuyingShareGood",
        });
    },
    // 活动商品倒计时
    minusRemainingSeconeds: function () {
        let activityNum = 0;
        const arr = this.data.remainingSecondsArr;
        arr.forEach((item, index, array) => {
            if (item === 0) {
                return;
            }
            activityNum++;
            array[index] = item - 1;
        });
        this.setData({
            remainingSecondsArr: arr,
            activityNum,
        });
        if (activityNum > 0) {
            setTimerId = setTimeout(() => {
                this.minusRemainingSeconeds();
            }, 1000);
        }
    },
    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function () {
    //     return {
    //         title: '这个商品真的太划算了，我已经下单了！', //转发页面的标题
    //     }
    // }
});
